import { loginService } from "@/service/login";
import { removeAccessToken, setAccessToken } from "@/utils/auth";
import { defineStore } from "pinia";
import { ref } from "vue";

const initState = { nickname: "", avatar: "", warehouse: "" };

export const useUserStore = defineStore(
	"user",
	() => {
		const userMsg = ref({ ...initState });
		const userInfo = ref<IUserInfo>();

		const setUserInfo = (val: IUserInfo) => {
			userInfo.value = val;
			setAccessToken(val.accessToken);
		};

		const clearUserInfo = () => {
			userInfo.value = null;
			userMsg.value = { ...initState };
		};
		// 一般没有reset需求，不需要的可以删除
		const reset = () => {
			userInfo.value = null;
			userMsg.value = { ...initState };
		};

		const logout = () => {
			userInfo.value = null;
			userMsg.value = { ...initState };
			removeAccessToken();
			uni.redirectTo({ url: "/pages/login/index" });
		};

		const login = async ({ email, password, callback, callbackError }) => {
			try {
				const loginRs = await loginService.login({
					email,
					password,
				});
				if (loginRs) {
					setUserInfo(loginRs);
					callback();
				}

				setUserMsg();
			} catch (error) {
				console.log(error);
				callbackError(error?.msg);
			}
		};

		const setUserMsg = async () => {
			const pRs = await loginService.getUserMsg();
			if (pRs && pRs.tenant) {
				const _d = pRs.tenant;
				const _u = pRs.user;
				let obj = { ...initState };
				obj.nickname = _u.nickname;
				obj.warehouse = _d.warehouse;

				userMsg.value = obj;
			}
		};

		return {
			userInfo,
			userMsg,
			setUserInfo,
			clearUserInfo,
			reset,
			logout,
			login,
			setUserMsg,
		};
	},
	{
		persist: true,
	},
);
